

import 'package:flutter/material.dart';

enum AlignPosition{
  left,right,top,bottom
}
/// 圆角矩形 + 三角提示布局
class TooltipPainter extends CustomPainter {
  //例如：底部往右边距离，右部往下距离，上部往右距离，左部往下距离
  final double arrowPosition;
  final AlignPosition ap;
  final Color? color;

  TooltipPainter({required this.arrowPosition, required this.ap,this.color});

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..color = color??const Color(0xff032141).withOpacity(0.9)
      ..style = PaintingStyle.fill;

    //三角形的底、高
    const double arrowHeight = 10;
    const double arrowWidth = 20;

    final Path path = Path();

    switch(ap){
      case AlignPosition.left:
        path..moveTo(0, arrowPosition)
          ..lineTo(-arrowHeight, arrowPosition+arrowWidth/2)
          ..lineTo(0, arrowPosition+arrowWidth);
        break;
      case AlignPosition.right:
        path..moveTo(size.width, arrowPosition)
          ..lineTo(size.width+arrowHeight, arrowPosition + arrowWidth/2)
          ..lineTo(size.width, arrowPosition+arrowWidth);
        break;
      case AlignPosition.top:
        path..moveTo(arrowPosition, /*0*/1)
          ..lineTo(arrowPosition+arrowWidth/2, -arrowHeight)
          ..lineTo(arrowPosition+arrowWidth, /*0*/1);//专门留1个像素的高度，避免中间小白线
        break;
      case AlignPosition.bottom:
        path..moveTo(arrowPosition-arrowWidth / 2, /*size.height*/size.height-1)////专门留1个像素的高度，避免中间小白线
          ..lineTo(arrowPosition, size.height + arrowHeight)
          ..lineTo(arrowPosition + arrowWidth / 2, /*size.height*/size.height-1);
        break;
    }
    path.close();

    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(const Offset(0, 0), Offset(size.width, size.height)),
            const Radius.circular(8)),
        paint);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
